<template>
  <div class="app-container">
    <el-card shadow="never">   
      <div class="filter-container" style="display: flex;align-items: baseline;">
        <el-select v-model="listQuery.source" placeholder="来源" class="filter-item" style="width: 180px;">
          <el-option v-for="item in [0,1,2]" :key="item" :label="item | statusFilter" :value="item" />
        </el-select>
        <el-button type="primary" class="filter-item" style="margin-left: 20px;" @click="getOrders">查询</el-button>

        <!-- <el-button  class="filter-item" icon="el-icon-upload" style="margin-left:20px;" type="primary" @click="handleImport">导入</el-button> -->
        <el-upload
          class="filter-item"
            action=""
            :before-upload="handleReaderFile"
            accept=".xlsx,.xls"
            :limit="1"
          style="display: inline-block;margin-left: 20px;"
          ref="upload">
          <el-button slot="trigger" :loading="btnLoading"  type="primary"><i class="el-icon-upload el-icon--left"></i>导入</el-button>
        </el-upload>
        <el-button  class="filter-item" icon="el-icon-download" :loading="exportLoading" style="margin-left:10px" type="primary" @click="exportData">导出</el-button>
        <el-switch
          style="margin-left:10px"
          active-color="#13ce66"
          active-text="启用IMEI池控制"
          inactive-text="禁用IMEI池控制"
          v-model="switchStatus"
          @change="handleSwitchChange"
          inactive-color="#ff4949">
        </el-switch>
      </div>
      <el-table :data="orders" style="width: 100%;" border >
        <el-table-column align="center" label="ID" width="50">
          <template v-slot="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="IMEI">
          <template v-slot="scope">
            {{ scope.row.imei }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="来源" >
          <template v-slot="scope">
            {{ scope.row.source | statusFilter }}
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="下单时间" >
          <template v-slot="scope">
            {{ scope.row.created_at | formatDate }}
          </template>
        </el-table-column> -->
      </el-table>
      <pagination v-show="total>0"  :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getOrders" />
    </el-card>
  </div>
</template>

<script>
import { getList,imeiImport,controlEnable,controlDisable,controlStatus} from '@/api/imei'
import { getToken } from '@/utils/auth'
import moment from "moment/moment";
import {checkPermission} from "@/utils/permission";
import Pagination from "@/components/Pagination/index.vue";
import {exportExcel} from "@/utils/excel";
import XLSX from "xlsx";

export default {
  name: 'ImeiList',
  components: {Pagination},
  data() {
    return {
      switchStatus: false, // 初始状态
      loading: false, // 用于防止多次切换
      token:'',
      btnLoading:false,
      exportLoading:false,
      fileTypes:['application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
      orders: [],
      total:0,
      listQuery:{
        page: 1,
        pageSize: 100,
        source:0
      },
      dialogVisible: false,
      dialogType: 'new',
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: '来源',
        1: '平台导入',
        2: '生产软件生成'
      }
      return statusMap[status]
    },
    formatDate(dateStr) {
      return moment(dateStr).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  created() {
    this.token = getToken()
    this.getOrders()
    this.getControlStatus()
  },
  methods: {
    checkPermission,
    getOrders() {
        getList(this.listQuery).then(response => {
          if (response.code === 0) {
              this.orders = response.data.list
              this.total = response.data.total
          } else {
            this.$message.error('读取数据错误')
          }
        })
    },
    getControlStatus() {
      controlStatus().then(response => {
          if (response.code === 20000) {
              this.switchStatus = response.status=='off'?false:true
              console.log(this.switchStatus)
          } else {
            this.$message.error('读取数据错误')
          }
        })
    },
    handleReaderFile(file){
      // this.batchUpdate.filename = file.name
      // 使用 FileReader 读取文件
      const reader = new FileReader();
      const that = this
      reader.onload = (e) => {
        const data = e.target.result;
        // 使用 XLSX 解析 Excel 文件内容
        const workbook = XLSX.read(data, { type: "binary" });
        // 获取第一个工作表的内容
        const firstSheetName = workbook.SheetNames[0];

        const worksheet = workbook.Sheets[firstSheetName];
        // 将工作表内容解析为 JSON
        const fileData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        let rawData = fileData.slice(1);
        if (rawData.length === 0) {
          that.$message.error('批量更新最数为1')
          return false
        }
        if (rawData.length > 100) {
          that.$message.error('批量更新最大数为100')
          return false
        }
        rawData = rawData.map((row) => row.map((cell) => String(cell || "")));
        let pool = [];
        for (let i = 0; i < rawData.length; i++) {
          for (let j = 0; j < rawData[i].length; j++) {
            pool.push(rawData[i][j]);
          }
        }
        imeiImport({"pool": pool}).then(response => {
          if (response.code === 20000) {
            this.$message.success("导入成功")
            this.getOrders()
          } else {
            this.$message.error('导入失败')
          }
        })
      };

      // 以二进制方式读取文件
      reader.readAsBinaryString(file);

      // 阻止默认上传行为
      return false;
    },
    exportData(){
      this.exportLoading = true
      const tHeader = ['ID', 'IMEI', '来源']
      const  list = this.orders.map(item => ({
        'ID': item.id,
        'IMEI': item.imei,
        '来源': item.source
      }))
      exportExcel(list, tHeader,'IMEI列表')
      setTimeout(() => {
        this.exportLoading = false
      }, 1.5 * 1000)
    },
    async handleSwitchChange(value) {
      // 防止重复提交
      if (this.loading) return;
      this.loading = true;
      if(value){
          controlEnable().then(response => {
            if (response.code === 20000) {
              this.$message.success("开启成功")
            }
            this.loading = false;
          }).catch(error => {
            this.switchStatus = false;
            this.loading = false;
          })
      }else{
        // this.switchStatus = false;
        controlDisable().then(response => {
          if (response.code === 20000) {
            this.$message.success("关闭成功")
          }
          this.loading = false;
        }).catch(error => {
          this.loading = false;
          this.switchStatus = true;
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
